/**
 * 云音乐缓存文件解码
 */

const fs = require('fs');
const path = require('path');
const toolsNode = require('../libs/tools-node');
const fileHeaderMarks = {
  MP3: [0x49, 0x44, 0x33],
  WAV: [0x52, 0x49, 0x46],
  wav: [0x57, 0x41, 0x56, 0x45],
  WMA: [0x30, 0x26, 0xB2],
};
// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let _ext = path.extname(from).toLowerCase();
let _name = path.basename(from, '.uc');

if (_ext === '.uc') {
  decodeFile();
}

function decodeFile() {
  return new Promise((resolve, reject) => {
    fs.readFile(from, (err, data) => {
      if (err || !data) reject('读取文件错误');
      let decrypted = data.map(v => (v ^ 0xA3));
      let to = path.join(path.dirname(from), `${_name}.mp3`);
      toolsNode.writeFileSync(to, decrypted);
      resolve();
    });
  });
};
